package com.sky.aop;



import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;


@Component
@Aspect
@Slf4j
public class AotoFillAspect {
    @Before("@annotation(com.sky.aop.AotoFill)")
    public void aotoFill(JoinPoint joinPoint) {
        log.info("自动填充");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        Method method = signature.getMethod();
        AotoFill annotation = signature.getMethod().getAnnotation(AotoFill.class);
        OperationType type = annotation.value();

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0){
            return;
        }
        Object datapojo = args[0];
        log.info("[自动填充]datapojo:{}",datapojo);
        if (type == OperationType.INSERT) {
//            log.info("[自动填充]method:{} insert.", method.getName());

            try {
                Method setCreateUser = datapojo.getClass().getDeclaredMethod("setCreateUser",Long.class);
                Method setCreateTime = datapojo.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);

                Method setUpdateUser = datapojo.getClass().getDeclaredMethod("setUpdateUser",Long.class);
                Method setUpdateTime = datapojo.getClass().getDeclaredMethod("setUpdateTime",LocalDateTime.class);

                setCreateUser.invoke(datapojo, BaseContext.getCurrentId());
                setUpdateUser.invoke(datapojo, BaseContext.getCurrentId());
                setCreateTime.invoke(datapojo, LocalDateTime.now());
                setUpdateTime.invoke(datapojo,LocalDateTime.now());
            } catch (Exception e) {
                e.printStackTrace();
                log.info("自动填充失败：{}",e.getMessage());
            }

        } else {
//            log.info("[自动填充]method:{} update.", method.getName());

            try {
               Method setUpdateUser = datapojo.getClass().getDeclaredMethod("setUpdateUser",Long.class);
               Method setUpdateTime = datapojo.getClass().getDeclaredMethod("setUpdateTime",LocalDateTime.class);

               setUpdateUser.invoke(datapojo, BaseContext.getCurrentId());
               setUpdateTime.invoke(datapojo, LocalDateTime.now());
            } catch (Exception e) {
                e.printStackTrace();
                log.info("自动填充失败：{}",e.getMessage());
            }
        }
    }
}